package cn.imvc.app.models;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import cn.imvc.app.entities.Account;
import cn.imvc.app.entities.Member;
import cn.imvc.app.repositories.MemberRepository;
import cn.imvc.core.ModelUtil;
import cn.imvc.data.domain.ViewRequest;
import cn.imvc.util.Md5;
/**
 * 
 * @author wujx
 * @time 2016年7月16日
 *
 */
@Service
public class MemberModelImpl implements MemberModel {
	@Autowired
	private MemberRepository memberRepository;
	@Autowired
	private AccountModel accountModel;
	
	/**
	 * 默认密码：123456
	 */
	private String defaultPwd = "123456";

	public Page<Member> findAll(ViewRequest viewRequest) {
		if(viewRequest == null){
			viewRequest = new ViewRequest();
		}
		viewRequest.getSort().put("id", "AEC");
		return memberRepository.findAll(viewRequest);
	}
	
	
	public void updateResetPassword(int id) {
		Member member = memberRepository.getOne(id);
		member.setPasswd(Md5.encode(Md5.encode(defaultPwd+member.getKey1())+member.getKey2()));
		memberRepository.saveAndFlush(member);
	}

	public Member getOne(int id) {
		return memberRepository.getOne(id);
	}


	public void update(Member member,int id) {
		Member oldMember = memberRepository.getOne(id);
		String theMobile = member.getMobile();
		if(theMobile != null && !theMobile .equals("")){
			oldMember.setMobile(theMobile);
		}
		Byte theState = member.getState();
		if(theState != 10){
			oldMember.setState(theState);
		}
		memberRepository.saveAndFlush(oldMember);
	}


	public void updateResetPaypwd(int id) {
		Account account = accountModel.getOne(id);
		account.setPaypwd(Md5.encode(Md5.encode(defaultPwd+account.getKey1())+account.getKey2()));
		accountModel.update(account);
	}


	@Override
	public List<Member> findAll() {
		return memberRepository.findAll();
	}


	@Override
	public List<Member> findAllByGuidLike(String s) {
		return memberRepository.findAllByGuidLike(s);
	}

}
